const WebSocket = require('ws');
const ws = new WebSocket.Server({ port: 8080 }, () => {
  console.log('socket start');
});

//每当有客户端链接的时候 就会有一个client对象
ws.on('connection', (client) => {
  let sendData = [
    {
      name: '张三',
      age: 22,
    },
    {
      name: '李四',
      age: 24,
    },
  ];
  //主动向前端发送消息
  client.send(JSON.stringify(sendData)); //数据只能传输字符串
  client.on('message', (msg) => {
    console.log('来自前端的数据：' + msg); //msg可以通过 msg.toString() 或者''+msg转换为字符串
  });

  client.on('close', (msg) => {
    console.log('前端主动断开了链接：');
  });
});
